﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Service.Core.Utils;
using System.Text;

namespace Service.Core.Filters
{
    public class DecryptionResourceFilter : Attribute, IAsyncResourceFilter, IOrderedFilter
    {
        public int Order => 1; // 先执行


        /// <summary>
        /// 在操作结果执行之后执行
        /// </summary>
        /// <param name="context"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void OnResourceExecuted(ResourceExecutedContext context)
        {
        }


        public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next)
        {
            //if (context.HttpContext.Request.ContentLength > 0)
            //{
            //    context.HttpContext.Request.EnableBuffering();
            //    using var reader = new StreamReader(context.HttpContext.Request.Body);
            //    var encryptedBody = await reader.ReadToEndAsync();
            //    context.HttpContext.Request.Body.Position = 0;
            //    if (!string.IsNullOrEmpty(encryptedBody))
            //    {
            //        var decryptedBody = PlayyerUtil.Decrypt(encryptedBody, "123456");
            //        var newBody = new MemoryStream(Encoding.UTF8.GetBytes(decryptedBody));
            //        context.HttpContext.Request.Body = newBody;
            //        context.HttpContext.Request.ContentLength = newBody.Length;
            //    }
            //}
            await next();
        }
    }
}
